#include "pgwslidewidget.h"

#include <QFile>
#include <QDebug>

class PgwSlideWidgetPrivate
{
public:
    QStringList images;
};

PgwSlideWidget::PgwSlideWidget(QWidget *parent) : QWebView(parent)
{
    d_ptr = new PgwSlideWidgetPrivate;
}

PgwSlideWidget::~PgwSlideWidget()
{
    delete d_ptr;
}

void PgwSlideWidget::setImages(const QStringList& images)
{
    d_ptr->images = images;
}

QStringList PgwSlideWidget::images() const
{
    return d_ptr->images;
}

bool PgwSlideWidget::render()
{
    QFile scriptFile(":./pgwslideshow.js");
    if (!scriptFile.open(QIODevice::ReadOnly)) {
        qDebug() << "failed to open script file.";
        return false;
    }

    QFile styleFile(":./pgwslideshow.css");
    if (!styleFile.open(QIODevice::ReadOnly)) {
        qDebug() << "failed to read style file.";
        return false;
    }

    QFile initFile(":./init.js");
    if (!initFile.open(QIODevice::ReadOnly)) {
        qDebug() << "failed to read initialization script.";
        return false;
    }

    QString script = scriptFile.readAll();
    QString style = styleFile.readAll();
    QString initScript = initFile.readAll();
    QString header = "<!DOCTYPE html><html><head><style>" + style +
                         "</style><body><div class=\"cntr mt20\"><ul class=\"pgwSlideshow\">";


    QString slideBody;

    foreach (auto img, d_ptr->images)
        slideBody +=QString("<li><img src=\"%1\">").arg(img);

    QString footer = "</ul></div><script>" + script + "</script><script>" + initScript + "</script></body></html>";
    QString html = header + slideBody + footer;
    qDebug() << html;
    setHtml(html);

    QFile outFile("G:/out.html");
    outFile.open(QIODevice::WriteOnly);
    outFile.write(html.toUtf8());
    return true;
}
